<template>
  <div>
    <el-row>
      <el-col :span="8"><div class="spanconent"></div></el-col>
      <el-col :span="8">
        <el-card>
          <el-form ref="loginFormRef"  :model="loginForm" :rules="loginFormRules" label-width="80px">
            <!-- 用户账号 -->
            <el-form-item label="用户账号" prop="username">
              <el-input v-model="loginForm.username"  ></el-input>
            </el-form-item>

            <!-- 用户密码 -->
            <el-form-item label="用户密码"  prop="password">
              <el-input v-model="loginForm.password" type="password"></el-input>
            </el-form-item>

            <el-button type="info" @click="login">登陆</el-button>
            <el-button type="danger" @click="clearInfo">清空</el-button>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="8"><div class="spanconent"></div></el-col>
    </el-row>
  </div>
</template>

<script>

import {mapMutations} from "vuex"

export default {
  data() {
    return {
    
      // 登陆表单
      loginForm : {
        username: "",
        password: ""
      },

     // 登陆表单规则
      loginFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
        ]
      }

    };
  },

  methods: {

    ...mapMutations(["setUserId","setUserName"]),
      // 登陆
    login(){ 

        this.$refs.loginFormRef.validate(async (valid)=>{
            
            if (!valid){
                return
            }
            
            const {data:res} = await this.$http.post("user/login",this.loginForm)

            console.log(res)

            if (res.meta.code === 200){
               
               this.$message.success("登陆成功!")
               window.sessionStorage.setItem("token",res.data.token)
               this.$store.commit("setUserId",res.data.userId)
               this.$store.commit("setUserName",res.data.username)
               this.$router.go(0)
            } else {

                return this.$message.error("用户名或者密码错误")
            }

            

        })
      },

     // 清空输入框信息
      clearInfo(){
          
         this.$refs.loginFormRef.resetFields()
      }
  },
};
</script>

<style></style>
